package com.example.my.controller;

import com.example.my.entity.User;
import com.example.my.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/my")
public class UserController {

    @Autowired
    private UserService userService;

    /* 1. 注册 */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            return ResponseEntity.ok(result ? "注册成功" : "注册失败");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /* 2. 登录 */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username,
                                   @RequestParam String password) {
        try {
            String token = userService.login(username, password);
            Map<String, String> resp = new HashMap<>();
            resp.put("token", token);
            return ResponseEntity.ok(resp);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /* 3. 当前用户信息 */
    @GetMapping("/current")
    public ResponseEntity<?> current(@RequestHeader("Authorization") String token) {
        User user = userService.getUserByToken(token);
        return user != null ? ResponseEntity.ok(user)
                : ResponseEntity.badRequest().body("未登录或 token 已失效");
    }

    /* 4. 退出登录 */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
        boolean success = userService.logout(token);
        return ResponseEntity.ok(success ? "退出成功" : "退出失败");
    }
}